﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using WmsApp.Service;
using WmsApp.Window;
using WmsApp.WmsService;

namespace WmsApp.WindowControl
{
    public class StockTackingController
    {
        private readonly IWrapService<StockTackingWrap> _wrapService = EntityServiceFactory.GetWrapService<StockTackingWrap, StockTackingWrapService>();
        private  ControlType _controlType = ControlType.None;
        private  StockTackingWrap _wrap = null;
        private readonly DateEdit _dateEditStockTackingTime;
        private readonly MemoEdit _memoEditRemark;
        private readonly TextEdit _textEditStockTackingCustomNo;
        private readonly TextEdit _textEditStockTackingDesc;
        private readonly TextEdit _textEditStockTackingNo;
        private readonly TextEdit _textEditStockTackingYearMonth;
        private readonly GridView _gridViewStockTackingDtl = null;

        public StockTackingController(DateEdit dateEditStockTackingTime,MemoEdit memoEditRemark,
            TextEdit textEditStockTackingCustomNo,TextEdit textEditStockTackingDesc,
            TextEdit textEditStockTackingNo, TextEdit textEditStockTackingYearMonth, GridView gridViewStockTackingDtl)
        {
            this._dateEditStockTackingTime = dateEditStockTackingTime;
            this._memoEditRemark = memoEditRemark;
            this._textEditStockTackingCustomNo = textEditStockTackingCustomNo;
            this._textEditStockTackingDesc = textEditStockTackingDesc;
            this._textEditStockTackingNo = textEditStockTackingNo;
            this._textEditStockTackingYearMonth = textEditStockTackingYearMonth;
            this._gridViewStockTackingDtl = gridViewStockTackingDtl;

            gridViewStockTackingDtl.GridControl.DataSourceChanged +=
                (o, e) => Style.RowStyleConditionController.AddStyleFormatCondition(gridViewStockTackingDtl, "StockQuantity", "StockQuantity   <>StockTackingQuantity + ExtNumeric1", Color.Red);
        }

        public void LoadStockTacking(string stockTackingNo)
        {
            this._wrap = _wrapService.GetWrap(stockTackingNo);
            _controlType = ControlType.Editing;
            this.DataBinding();
        }

        public bool WrapExist
        {
            get
            {
                if (_wrap != null && _wrap.PStockTacking != null)
                    return true;
                return false;
            }
        }

        private void DataBinding()
        {
            this._textEditStockTackingCustomNo.DataBindings.Clear();
            this._textEditStockTackingCustomNo.DataBindings.Add("EditValue", _wrap.PStockTacking, "StockTackingCustomNo");

            this._textEditStockTackingDesc.DataBindings.Clear();
            this._textEditStockTackingDesc.DataBindings.Add("EditValue", _wrap.PStockTacking, "StockTackingDesc");

            this._textEditStockTackingNo.DataBindings.Clear();
            this._textEditStockTackingNo.DataBindings.Add("EditValue", _wrap.PStockTacking, "StockTackingNo");

            this._textEditStockTackingYearMonth.DataBindings.Clear();
            this._textEditStockTackingYearMonth.DataBindings.Add("EditValue", _wrap.PStockTacking, "StockTackingYearMonth");

            this._dateEditStockTackingTime.DataBindings.Clear();
            this._dateEditStockTackingTime.DataBindings.Add("EditValue", _wrap.PStockTacking, "StockTackingTime",true,DataSourceUpdateMode.OnValidation);

            this._memoEditRemark.DataBindings.Clear();
            this._memoEditRemark.DataBindings.Add("EditValue", _wrap.PStockTacking, "Remark");

            this._gridViewStockTackingDtl.GridControl.DataSource = _wrap.PStockTackingDtl;
        }

        public void AddInStockBillDtl(List<StockTackingDtl> list)
        {
            foreach (var stockTackingDtl in list)
            {
                stockTackingDtl.StockTackingNo = _wrap.PStockTacking.StockTackingNo;
                _wrap.PStockTackingDtl.Add(stockTackingDtl);
            }
           
            this._gridViewStockTackingDtl.GridControl.RefreshDataSource();
        }

        public void NewStockTacking()
        {
            if (_wrap != null)
            {
                if (_wrap.IsNeedSaved())
                {
                    if (DialogResult.OK == XtraMessageBox.Show(_wrap.PStockTacking.StockTackingNo + "当前入库单已修改，要保存吗？", "提问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                    {
                        SaveStockTacking();
                    }
                }
            }
            _wrap = new StockTackingWrap();
            _wrap.PStockTacking = StockTacking.CreateStockTacking();
            _wrap.PStockTackingDtl = new List<StockTackingDtl>();
            _controlType = ControlType.New;
            this.DataBinding();
        }

        private bool Save()
        {
            if (_wrap != null && _wrap.PStockTacking != null)
            {
                //先校验出库单明细
                string msg = string.Empty;
                bool b = ValidateStockTacking(out msg);
                if (!b)
                {
                    XtraMessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
            }
            else
            {
                return false;
            }
            var client = Factory.WmsServiceFactory.GetServiceClient();

            if (_wrap.PStockTacking.WcfEntityState == EntityState.Added
                && _wrap.PStockTacking.StockTackingNo == Constant.NewStockTackingId)
            {
                var stockTackingNo = client.GetStockTackingId();
                _wrap.PStockTacking.StockTackingNo = stockTackingNo;
                foreach (var stockTackingDtl in _wrap.PStockTackingDtl)
                {
                    stockTackingDtl.StockTackingNo = stockTackingNo;
                }
            }
            _wrapService.SaveWrap(_wrap);

            return true;
        }

        private bool ValidateStockTacking(out string msg)
        {
            msg = String.Empty;
            if (_wrap != null && _wrap.PStockTacking != null)
            {
                if ( _wrap.PStockTackingDtl.Count==0)
                {
                    msg = "盘库单明细为0！";
                    return false;
                }
            }
            else
            {
                msg = "不存在盘库单！";
                return false;
            }
            return true;
        }

        public bool NewGoodsCodeInDtlList(string newGoodsCode)
        {
            if( this._wrap == null)
            {
                Exceptions.ExceptionHandler.ShowException("没有盘库单，可能没有新增盘库单！");
                return false;
            }
            var query = from o in this._wrap.PStockTackingDtl
                        where o.NewGoodsCode == newGoodsCode
                        select o;
            if(query.Count<StockTackingDtl>()>0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 出库调整
        /// </summary>
        public void OutRange()
        {
            if (this._wrap == null)
            {
                Exceptions.ExceptionHandler.ShowException("没有盘库单！");
                return;
            }
            if ( _wrap.PStockTacking!= null&& _wrap.PStockTacking.WcfEntityState != EntityState.Added)
            {
                try
                {
                    var list = _wrap.PStockTackingDtl.Where(stockTackingDtl => stockTackingDtl.IsSelected).ToList();
                    var form = MainFormControl.GenerateForm<FormOut>(FormMain.FormMainInstance);
                    form.NewStockTacking(list);
                    form.SetTabPageIndex(2);
                    form.CmdEnableControl();
                }
                catch (Exception exception)
                {
                    XtraMessageBox.Show(exception.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            
            }
            else
            {
                Exceptions.ExceptionHandler.ShowException("请先保存，再执行该操作！");
            }
        }

        public void SaveStockTacking()
        {
            if (Save())
            {
                XtraMessageBox.Show(_wrap.PStockTacking.StockTackingNo + "保存成功！", "提示", MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                LoadStockTacking(_wrap.PStockTacking.StockTackingNo);
            }
            else
            {
                XtraMessageBox.Show( "保存失败！", "提示", MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

        public void AllSelect()
        {
            if (this._wrap == null)
            {
                Exceptions.ExceptionHandler.ShowException("没有盘库单！");
                return;
            }
            if (_wrap.PStockTacking != null &&
            _wrap.PStockTacking.WcfEntityState != EntityState.Added)
            {
                foreach (var stockTackingDtl in _wrap.PStockTackingDtl)
                {
                    stockTackingDtl.IsSelected = true;
                }
                this._gridViewStockTackingDtl.GridControl.RefreshDataSource();
            }
            else
            {
                Exceptions.ExceptionHandler.ShowException("请先保存，再执行该操作！");
            }
        }

        public void AllNotSelect()
        {
            if (this._wrap == null)
            {
                Exceptions.ExceptionHandler.ShowException("没有盘库单！");
                return;
            }
            if (_wrap.PStockTacking != null &&
            _wrap.PStockTacking.WcfEntityState != EntityState.Added)
            {
                foreach (var stockTackingDtl in _wrap.PStockTackingDtl)
                {
                    stockTackingDtl.IsSelected = false;
                }
                this._gridViewStockTackingDtl.GridControl.RefreshDataSource();
            }
            else
            {
                Exceptions.ExceptionHandler.ShowException("请先保存，再执行该操作！");
            }
        }

        public void DeleteDtl()
        {
            if (this._wrap == null)
            {
                Exceptions.ExceptionHandler.ShowException("没有盘库单！");
                return ;
            }
            if (_wrap.PStockTacking != null && _wrap.PStockTackingDtl.Count>0)
            {
                var deleteList = new List<StockTackingDtl>();
                foreach (var stockTackingDtl in _wrap.PStockTackingDtl)
                {
                    if(stockTackingDtl.IsSelected )
                    {
                        deleteList.Add(stockTackingDtl);
                    }
                }

                if(deleteList.Count >0)
                {
                    if(System.Windows.Forms.DialogResult.Yes == 
                        XtraMessageBox.Show(
                        string.Format("确实要删除选中的{0}行明细吗？",deleteList.Count),
                        "提问",MessageBoxButtons.YesNo,MessageBoxIcon.Question))
                    {
                        var client = Factory.WmsServiceFactory.GetServiceClient();
                        client.DeleteStockTackingDtlList(deleteList);
                        foreach (var stockTackingDtl in deleteList)
                        {
                            _wrap.PStockTackingDtl.Remove(stockTackingDtl);
                        }
                        this._gridViewStockTackingDtl.GridControl.RefreshDataSource();
                    }
                }
            }
        }
    }
}